package com.example.demo.controller;

import com.example.demo.model.request.FrontendRequest;
import com.example.demo.model.response.ApiResponse;
import com.example.demo.model.response.FrontendResponse;
import com.example.demo.service.PredictionService;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/prediction")
public class PredictionController {

    private final PredictionService predictionService;

    public PredictionController(PredictionService predictionService) {
        this.predictionService = predictionService;
    }

    /**
     * 接收前端输入，处理后返回结果
     */
    @PostMapping("/calculate")
    public FrontendResponse calculate(@RequestBody FrontendRequest request) {
        try {
            // 调用服务层获取结果
            ApiResponse apiResponse = predictionService.predict(request);
            // 包装成前端需要的响应格式 - 使用setter方法而不是构造函数
            FrontendResponse response = new FrontendResponse();
            response.setCode(200);
            response.setMsg("计算成功");
            response.setData(apiResponse.getPrediction());
            return response;
        } catch (Exception e) {
            // 异常处理
            FrontendResponse response = new FrontendResponse();
            response.setCode(500);
            response.setMsg("计算失败：" + e.getMessage());
            response.setData(null);
            return response;
        }
    }
}